//
// OpenArrow Utility Library
// Copyright (c) 2006
// by OpenArrow Software ( http://www.openarrow.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace OpenArrow.Utils
{
    /// <summary>
    /// Provides an implementation of <see cref="TextReader"/> that represents a chained view over a list of existing <see cref="TextReader"/> objects
    /// </summary>
    /// <remarks>
    /// This is a simple helper class that reads text from multiple readers. When this reader is created,
    /// it must be provided with a Reader Chain, which is an ordered list of <see cref="TextReader"/> objects.
    /// When <see cref="ChainedTextReader.Read"/> is called, the call is forwarded to the current reader. If that
    /// reader has no more characters to read, then the position is advanced and the call is forwarded to the next reader
    /// in the chain.
    /// </remarks>
    public class ChainedTextReader : TextReader
    {
        private List<TextReader> readerChain;
        private int position;

        /// <summary>
        /// Constructs a new instance of the <see cref="ChainedTextReader"/> object
        /// </summary>
        /// <param name="readerChain">An ordered list of readers</param>
        public ChainedTextReader(IEnumerable<TextReader> readerChain)
        {
            this.readerChain = new List<TextReader>(readerChain);
        }

        /// <summary>
        /// Reads a character from the current text reader, advancing the position of the chained reader if there is no
        /// more data in the current reader
        /// <seealso cref="TextReader.Read()"/>
        /// </summary>
        /// <remarks>This method ONLY returns -1 if the current reader and ALL readers after it returned -1.</remarks>
        /// <returns>The character read, or -1 if there are no characters remaining to read</returns>
        /// <exception cref="System.IO.IOException">An I/O error occurs</exception>
        /// <exception cref="System.ObjectDisposedException">The <see cref="TextReader"/> is closed</exception>
        public override int Read()
        {
            // No more readers
            if (position >= readerChain.Count)
                return -1;

            // Read a character
            int read = readerChain[position].Read();

            // If there are no more at this position...
            if (read == -1)
            {
                // And there are no more readers in the chain
                if (position == readerChain.Count - 1)
                    return -1; // No more readers

                // Move to the next reader and try again (recursive until we reach the end of the chain, or a reader that has data
                position++;
                return Read();    
            }
            return read;
        }

        /// <summary>
        /// Peeks at a character from the current text reader without advancing the position
        /// <seealso cref="TextReader.Peek()"/>
        /// </summary>
        /// <remarks>
        /// This method forwards the call on to the current reader, and if no characters are available in that reader, then the next reader is checked
        /// and so on. However, the current position within the reader chain is not changed
        /// </remarks>
        /// <returns>The next character in the reader, or -1 if there are no characters remaining to read</returns>
        /// <exception cref="System.IO.IOException">An I/O error occurs</exception>
        /// <exception cref="System.ObjectDisposedException">The <see cref="TextReader"/> is closed</exception>
        public override int Peek()
        {
            return InternalPeek(position);
        }

        private int InternalPeek(int localposition)
        {
            // No more readers
            if (localposition >= readerChain.Count)
                return -1;

            // Peek a character
            int read = readerChain[localposition].Peek();

            // If there are no more at this position...
            if (read == -1)
            {
                // And there are no more readers in the chain
                if (localposition == readerChain.Count - 1)
                    return -1; // No more readers

                // Move to the next reader and try again (recursive until we reach the end of the chain, or a reader that has data
                localposition++;
                return InternalPeek(localposition);
            }
            return read;
        }
    }
}
